package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional//开启事务
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    //分类列表
    @Override
    public List<Category> findList() {

        return categoryMapper.findList();
    }
//分类增加
    @Override
    public void save(Category category) {
        category.setId(IdUtil.getSnowflake(1,1).nextId());
        /*category.setCreateUser(1L);
        category.setCreateTime(new Date());
        category.setUpdateTime(new Date());
        category.setUpdateUser(1L);*/
        categoryMapper.save(category);
    }
//修改
    @Override
    public void update(Category category) {
       /* category.setUpdateUser(1L);
        category.setUpdateTime(new Date());*/

        categoryMapper.update(category);
    }
//删除分类
    @Override
    public ResultInfo deleteById(Long id) {
     Integer count1=  categoryMapper.countDishCategoryId(id);
        if (count1>0) {
            return ResultInfo.error("菜品还有该分类,无法删除");
        }
       Integer count2= categoryMapper.countSetmealCategoryId(id);
        if (count2>0) {
            return ResultInfo.error("套餐还有该分类,无法删除");
        }

        categoryMapper.deleteById(id);
        return ResultInfo.success(null);
    }
//根据type查询
    @Override
    public List<Category> findByType(Integer type) {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getType, type);
        List<Category> categoryList = categoryMapper.selectList(wrapper);

        return categoryList;
    }
}
